package com.pay.ioopos.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.pay.ioopos.Application;


public class NetworkService extends IntentService {
    private static Intent service;
    private static boolean available = false;
    private static Handler handler = new Handler();
    private static Thread thread;
    private static final NetworkCallback callback = new NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            available = true;
            if (null != thread) {
                thread.interrupt();
            }
        }

        @Override
        public void onLost(Network network) {
            available = false;
            if (null != thread) {
                thread.interrupt();
            }
            thread = new Thread(() -> {
                try {
                    if (null == Looper.myLooper()) {
                        Looper.prepare();
                    }
                    while (true) {
                        handler.post(() -> Toast.makeText(Application.getContext(), " 亲，没网络！", Toast.LENGTH_SHORT).show());
                        Thread.sleep(5000);
                    }
                } catch (InterruptedException ignored) {

                }
            });
            thread.start();
        }
    };

    public NetworkService() {
        super("NetworkService");
    }

    public static void start(Context context) {
        if (null == service) {
            service = new Intent(context, NetworkService.class);
            context.startService(service);
        }
    }

    public static boolean isNetworkAvailable() {
        return available;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.registerNetworkCallback(new NetworkRequest.Builder().build(), callback);
    }

}
